#include "http_decoder.h"

HttpDecoder::HttpDecoder()
{
	pHttpData = NULL;
	reqtype = NONHTTP;
	httptype = NON_HTTPTYPE;
}

HttpDecoder::HttpDecoder(const u_char* packetcontent)
{
	pHttpData = (char *)(packetcontent+sizeof(struct ether_header)+sizeof(struct iphdr)+sizeof(struct tcphdr));
	reqtype = NONHTTP;
	httptype = NON_HTTPTYPE;
}

HttpDecoder::~HttpDecoder()
{
	pHttpData = NULL;
	delete [] pHttpData;
}

HTTPTYPE HttpDecoder::GetHttpType()
{
	if((pHttpData[0] == 'H') && (pHttpData[1] == 'T') && (pHttpData[2] == 'T') && (pHttpData[3] == 'P'))
		httptype = SERVER_RESPONSE;
	else if((pHttpData[0]=='G') && (pHttpData[1]=='E') && (pHttpData[2]=='T'))
	{
		reqtype = GET;
		httptype = CLIENT_REQUEST;
	}
	else if((pHttpData[0]=='P') && (pHttpData[1]=='O') && (pHttpData[2]=='S') && (pHttpData[3] == 'T'))
	{
		reqtype = POST;
		httptype = CLIENT_REQUEST;
	}
	else if((pHttpData[0] == 'H') && (pHttpData[1] == 'E') && (pHttpData[2] == 'A') && pHttpData[3] == 'D')
	{
		reqtype =  HEAD;
		httptype = CLIENT_REQUEST;
	}
	else if((pHttpData[0] == 'P') && (pHttpData[1] == 'U') && (pHttpData[2] == 'T'))
	{
		reqtype =  PUT;
		httptype = CLIENT_REQUEST;
	}
	else if((pHttpData[0] == 'D') && (pHttpData[1] == 'E') && (pHttpData[2] == 'L') && (pHttpData[3] == 'E') && (pHttpData[4] == 'T') && (pHttpData[5] == 'E'))
	{
		reqtype =  DEL;
		httptype = CLIENT_REQUEST;
	}
	else if((pHttpData[0] == 'O') && (pHttpData[1] == 'P') && (pHttpData[2] == 'T') && (pHttpData[3] == 'I') && (pHttpData[4] == 'O') && (pHttpData[5] == 'N') && (pHttpData[6] == 'S'))
	{
		reqtype =  OPTIONS;
		httptype = CLIENT_REQUEST;
	}
	else if ((pHttpData[0] == 'T') && (pHttpData[1] == 'R') && (pHttpData[2] == 'A') && (pHttpData[3] == 'C') && (pHttpData[4] == 'E'))
	{
		reqtype =  TR;
		httptype = CLIENT_REQUEST;
	}
	else
		httptype = NON_HTTPTYPE;
	return httptype;
}

char * HttpDecoder::GetHttpData()
{
	return pHttpData;
}

REQUEST HttpDecoder::GetRequestType()
{
	return reqtype;
}

int HttpDecoder::GetStatusCode()
{
	if (httptype == SERVER_RESPONSE)
	{
		char * data = pHttpData;
		data = data + 9 * sizeof(char);
		char scode[4];
		scode[0] = *data;
		scode[1] = *++data;
		scode[2] = *++data;
		scode[3] = '\0';
		return atoi(scode);
	}
	else
		return -1;
}